package org.github.manx98.jlibhac.tools.fssystem;

import org.github.manx98.jlibhac.fs.IStorage;

import javax.crypto.ShortBufferException;
import java.io.IOException;

/**
 * @author Manx98
 * @version 1.0
 * @since 2022/10/3 20:22
 */
public class Aes128XtsStorage extends SectorStorage {
    private static final int BlockSize = 0x10;
    private final boolean decryptRead;
    private final byte[] key1;
    private final byte[] key2;
    private Aes128XtsTransform readTransform;

    public Aes128XtsStorage(IStorage baseStorage, byte[] key1, byte[] key2, int sectorSize, boolean leaveOpen, boolean decryptRead) {
        super(baseStorage, sectorSize, leaveOpen);
        if (key1 == null) throw new IllegalArgumentException("key1 cannot be null");
        if (key2 == null) throw new IllegalArgumentException("key2 cannot be null");
        if (key1.length != BlockSize || key2.length != BlockSize)
            throw new IllegalArgumentException("Keys must be " + BlockSize + " bytes long");
        this.decryptRead = decryptRead;
        this.key1 = key1;
        this.key2 = key2;
    }

    @Override
    public void read(long offset, byte[] destination, int destOffset, int len) throws IOException {
        long sectorIndex = offset / sectorSize;
        if (readTransform == null) readTransform = new Aes128XtsTransform(key1, key2, decryptRead);
        super.read(offset, destination, destOffset, len);
        readTransform.transformBlock(destination, destOffset, len, sectorIndex);
    }
}
